package com.example.design.practice.dark.v2;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 支持根据业务功能标识（feature key），快速查询灰度规则（DarkFeature）
 * 为了避免配置文件中的灰度规则热更新时，覆盖掉编程实现的灰度规则，在 DarkRule 中，
 * 对从配置文件中加载的灰度规则和编程实现的灰度规则分开存储
 */
public class DarkRule {
    /**
     * 从配置文件中加载的灰度规则
     */
    private Map<String, IDarkFeature> darkFeatures = new HashMap<>();
    /**
     * 编程实现的灰度规则
     */
    private ConcurrentHashMap<String, IDarkFeature> programmedDarkFeatures = new ConcurrentHashMap<>();

    public void addProgrammedDarkFeatures(String featureKey, IDarkFeature darkFeature) {
        programmedDarkFeatures.put(featureKey, darkFeature);
    }

    public void setDarkFeatures(Map<String, IDarkFeature> newDarkFeatures) {
        this.darkFeatures = newDarkFeatures;
    }


    public IDarkFeature getDarkFeature(String featureKey) {
        IDarkFeature iDarkFeature = programmedDarkFeatures.get(featureKey);
        if (iDarkFeature != null) {
            return iDarkFeature;
        }
        return darkFeatures.get(featureKey);
    }
}